package com.jz.digital.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.util.Log;

import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Locale;

/**
 * @author: lyw
 * @description: ${TODO}{获取APP信息的辅助类}
 * @date: 2016/11/22 15:33
 */
public class AppUtil {
    private static final String TAG = "AppUtil";

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static boolean isGpsOpen(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return gps || network;
    }

    /**
     * 强制帮用户打开GPS
     *
     * @param context
     */
    public static void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }
    /**
     * 判断是否是深色模式
     * @param context
     * @return
     */
    public static boolean isNightMode(Context context) {
        try {
            return (context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
        } catch (Exception ex) {

        }
        return false;
    }
    /**
     * 是否是中国地区
     *
     * @return
     */
    public static boolean isInChina() {
        return Locale.getDefault().getCountry().equals("CN");
    }

    public static int getAppMaxMemory() {
        Runtime rt = Runtime.getRuntime();
        long maxMemory = rt.maxMemory();
//        log.i());
//        tvMsg.setText("maxMemory:"+Long.toString(maxMemory/(1024*1024))+"MB");
        int mb = (int) (maxMemory / (1024 * 1024));
        return mb;
    }

    public static String getLanguage(Context context) {
        if (context == null) return "";
        Locale locale = context.getResources().getConfiguration().locale;
        return locale.getLanguage();
    }

    /**
     * 判断整个app项目是否在用户操作界面
     * b
     */
    public static boolean appIsRunning(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = am.getRunningAppProcesses();
        if (appProcesses == null || appProcesses.size() == 0) return false;
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (TextUtils.equals(appProcess.processName, context.getPackageName())) {
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND ||
                        appProcess.importanceReasonCode == 2) {
                    return false;
                } else {
                    return true;
                }
            }
        }
        return true;
    }

    /**
     * 根据包名获取程序图标
     *
     * @param context
     * @param packname 应用包名
     * @return
     */
    public static Drawable getAppIconByPackageName(Context context, String packname) {
        try {
            //包管理操作管理类
            PackageManager pm = context.getPackageManager();
            //获取到应用信息
            ApplicationInfo info = pm.getApplicationInfo(packname, 0);
            return info.loadIcon(pm);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersionName(Context context) {
        if (context == null) return "";
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取版本code
     *
     * @return
     */
    public static int getVersionCode(Context context) {
        if (context == null) return 0;
        PackageManager packageManager = context.getApplicationContext().getPackageManager();
        PackageInfo packageInfo;
        try {
            packageInfo = packageManager.getPackageInfo(context.getApplicationContext().getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取App名字
     *
     * @return
     */
    public static String getAppName(Context context) {
        if (context == null) return "";
        try {
            Context applicationContext = context.getApplicationContext();
            PackageManager packageManager = applicationContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(applicationContext.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return applicationContext.getResources().getString(labelRes);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取手机厂商
     *
     * @return
     */
    public static String getDeviceBrand() {
        return Build.BRAND;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getPhoneModel() {
        return Build.MODEL;
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersionName() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 获取当前手机系统版本
     *
     * @return
     */
    public int getSystemVersionCode() {
        return Build.VERSION.SDK_INT;
    }


    @SuppressLint("MissingPermission")
    public static String getPhoneInfo(Context context) {
        TelephonyManager mTm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("IMEI:" + mTm.getDeviceId());
        stringBuffer.append(",type:" + Build.MODEL);
        stringBuffer.append(",SDK_INT:" + Build.VERSION.SDK_INT);
        stringBuffer.append(",RELEASE:" + Build.VERSION.RELEASE);
        stringBuffer.append(",number:" + mTm.getLine1Number());
        return stringBuffer.toString();
    }

    public static String getPhoneLogInfo(Context context) {
        if (context == null) return "";
        TelephonyManager mTm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("品牌:" + Build.MANUFACTURER);
        stringBuffer.append("\n设备名称:" + Build.MANUFACTURER + Build.DEVICE);
        stringBuffer.append("\n型号:" + Build.MODEL);
        stringBuffer.append("\n版本号:" + Build.DISPLAY);
        stringBuffer.append("\n处理器:" + getCpuInfo()[0]);
        stringBuffer.append("\n运行内存:" + getAvailMemory(context));
        String[] size = getSDTotalSize();
        stringBuffer.append("\n手机存储: 可用空间:" + size[1] + ",总容量:" + size[0] + ",已使用空间:" + size[2]);
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        stringBuffer.append("\n分辨率:" + displayMetrics.widthPixels + "*" + displayMetrics.heightPixels);
        stringBuffer.append("\nandroid版本:" + Build.VERSION.SDK_INT);
        stringBuffer.append("\napp版本:" + getVersionName(context));
        return stringBuffer.toString();
    }

    private static String[] getCpuInfo() {
        String str1 = "/proc/cpuinfo";
        String str2 = "";
        String[] cpuInfo = {"", ""};  //1-cpu型号  //2-cpu频率
        String[] arrayOfString;
        try {
            FileReader fr = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            for (int i = 2; i < arrayOfString.length; i++) {
                cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
            }
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            cpuInfo[1] += arrayOfString[2];
            localBufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cpuInfo;
    }


    /**
     * 根据路径获取内存状态
     *
     * @return
     */
    public static String getMemoryInfo(Context context) {
        // 获得手机内部存储控件的状态
        File dataFileDir = Environment.getDataDirectory();
        // 获得一个磁盘状态对象
        StatFs stat = new StatFs(dataFileDir.getPath());

        long blockSize = stat.getBlockSize();   // 获得一个扇区的大小

        long totalBlocks = stat.getBlockCount();    // 获得扇区的总数

        long availableBlocks = stat.getAvailableBlocks();   // 获得可用的扇区数量

        // 总空间
        String totalMemory = Formatter.formatFileSize(context, totalBlocks * blockSize);
        // 可用空间
        String availableMemory = Formatter.formatFileSize(context, availableBlocks * blockSize);

        return "总空间: " + totalMemory + "\n可用空间: " + availableMemory;
    }

    //  总容量，未使用，已使用
    private static String[] getSDTotalSize() {
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        long size = sf.getBlockSize();//SD卡的单位大小
        long total = sf.getBlockCount();//总数量
        long available = sf.getAvailableBlocks();//可使用的数量
        DecimalFormat df = new DecimalFormat();
        df.setGroupingSize(3);//每3位分为一组
//总容量
        String totalSize = (size * total) / 1024 >= 1024 ? df.format(((size * total) / 1024) / 1024) + "MB" : df.format((size * total) / 1024) + "KB";
//未使用量
        String avalilable = (size * available) / 1024 >= 1024 ? df.format(((size * available) / 1024) / 1024) + "MB" : df.format((size * available) / 1024) + "KB";
//已使用量
        String usedSize = size * (total - available) / 1024 >= 1024 ? df.format(((size * (total - available)) / 1024) / 1024) + "MB" : df.format(size * (total - available) / 1024) + "KB";
        String[] totalSizeStr = new String[]{totalSize, avalilable, usedSize};
        return totalSizeStr;
    }

    /**
     * 获取手机内存大小
     *
     * @return
     */
    public static String getTotalMemory(Context context) {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小

            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }

            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() / 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
            localBufferedReader.close();

        } catch (IOException e) {
        }
        return Formatter.formatFileSize(context, initial_memory);// Byte转换为KB或者MB，内存大小规格化
    }

    /**
     * //获得系统可用内存信息
     *
     * @return
     */
    private static String getAvailMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(context, mi.availMem);
    }

    /**
     * 获取手机IMEI号
     */
    public static String getIMEI(Context context) {
        String imei = "";
        try {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                imei = telephonyManager.getDeviceId();
            }
        } catch (Exception e) {
        }
        if (TextUtils.isEmpty(imei)) {
            imei = getAndroidId(context);
        }
        return imei;
    }

    public static String getAndroidId(Context context) {
        try {
            return Settings.System.getString(
                    context.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 安装app
     *
     * @param context
     * @param filePath apk路径
     */
    public static void installApp(Context context, String filePath) {
        File file = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 兼容7.0
            uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // 兼容8.0
                boolean hasInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    //注意这个是8.0新API  ,跳转到设置-允许安装未知来源-页面
                    intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    return;
                }
            }
        } else {
            uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }

        if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            context.startActivity(intent);
        }
    }

    /**
     * 根据包名判断是否安装了应用
     *
     * @param context
     * @param pageageName
     * @return
     */
    public static boolean isInstallAppByPackageName(Context context, String pageageName) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(pageageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        return packageInfo != null;
    }

    /**
     * 获取pid进程
     *
     * @param cxt
     * @param pid
     * @return
     */
    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

    /**
     * 是否安装了fackbook
     *
     * @param context
     * @return
     */
    public static boolean isInstallFackbook(Context context) {
        return isInstallAppByPackageName(context, "com.facebook.katana");
    }

    /**
     * 是否安装了qq
     *
     * @param context
     * @return
     */
    public static boolean isInstallQQ(Context context) {
        return isInstallAppByPackageName(context, "com.tencent.mqq");
    }

    /**
     * 是否安装了qq2012
     *
     * @param context
     * @return
     */
    public static boolean isInstallQQ2012(Context context) {
        return isInstallAppByPackageName(context, "com.tencent.mobileqq");
    }

    /**
     * 是否安装了91熊猫看书
     *
     * @param context
     * @return
     */
    public static boolean isInstall91ReadBook(Context context) {
        return isInstallAppByPackageName(context, "com.nd.android.pandareader");
    }

    /**
     * 是否安装了微信
     *
     * @param context
     * @return
     */
    public static boolean isInstallWeChat(Context context) {
        return isInstallAppByPackageName(context, "com.tencent.mm");
    }

    /**
     * 是否安装了chrome浏览器
     *
     * @param context
     * @return
     */
    public static boolean isInstallChrome(Context context) {
        return isInstallAppByPackageName(context, "com.android.chrome");
    }

    /**
     * 是否安装了opera浏览器
     *
     * @param context
     * @return
     */
    public static boolean isInstallOpera(Context context) {
        return isInstallAppByPackageName(context, "com.opera.browser");
    }

    /**
     * 是否安装了firefox浏览器
     *
     * @param context
     * @return
     */
    public static boolean isInstallFireFox(Context context) {
        return isInstallAppByPackageName(context, "org.mozilla.firefox");
    }

    /**
     * 是否安装了VeryFit
     *
     * @param context
     * @return
     */
    public static boolean isInstallVeryFit(Context context) {
        return isInstallAppByPackageName(context, "com.veryfit2hr.second");
    }

    /**
     * 跳转权限设置界面
     *
     * @param activity
     */
    public static void jumpSetting(Activity activity) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", activity.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", activity.getPackageName());
        }
        activity.startActivity(intent);
    }

    /**
     * 是否打开了通知权限
     *
     * @return
     */
    public static boolean isNotificationEnabled(Context context) {
        ContentResolver contentResolver = context.getContentResolver();
        String enabledListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners");
        //先屏蔽
        //            return enabledListeners.contains(NotificationService.class.getNameRes());
        return !TextUtils.isEmpty(enabledListeners);
    }

    /**
     * 判断服务是否开启
     */
    public static boolean isServiceRunning(Context context, String proServiceName) {
        ActivityManager manager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        if (manager == null) {
            return false;
        }
        List<ActivityManager.RunningServiceInfo> runningService = manager
                .getRunningServices(300);
        if (runningService == null) {
            return false;
        }
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName()
                    .equals(proServiceName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断APP是否在运行
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isAppRunning(Context context, String packageName) {
        int uid = getPackageUid(context, packageName);
        return isProcessRunning(context, uid);
    }

    /**
     * 获取uid
     *
     * @param context
     * @param packageName
     * @return
     */
    public static int getPackageUid(Context context, String packageName) {
        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
            if (applicationInfo != null) {
                return applicationInfo.uid;
            }
        } catch (Exception e) {
            return -1;
        }
        return -1;
    }

    /**
     * 判断APP是否运行
     *
     * @param context
     * @param uid
     * @return
     */
    public static boolean isProcessRunning(Context context, int uid) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServiceInfos = am.getRunningServices(200);
        if (runningServiceInfos.size() > 0) {
            for (ActivityManager.RunningServiceInfo appProcess : runningServiceInfos) {
                if (uid == appProcess.uid) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 打开网络设置界面
     */
    public static void openSetting(Activity activity) {
        Intent intent = new Intent("/");
        ComponentName cm = new ComponentName("com.android.settings",
                "com.android.settings.WirelessSettings");
        intent.setComponent(cm);
        intent.setAction("android.intent.action.VIEW");
        activity.startActivityForResult(intent, 0);
    }

    public static void toAPPMarket(Context context) {
        try {
            Intent intent1 = new Intent(Intent.ACTION_VIEW);
            intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent1.setData(Uri.parse("market://details?id=" + context.getPackageName()));
            intent1.setPackage(context.getPackageName());
            if (intent1.resolveActivity(context.getPackageManager()) != null) {
                context.startActivity(intent1);
            } else {
                Intent intent2 = new Intent(Intent.ACTION_VIEW);
                intent2.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName()));
                intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (intent2.resolveActivity(context.getPackageManager()) != null) {
                    context.startActivity(intent2);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到应用市场
     *
     * @param context
     * @param pkg
     */
    public static void toAPPMarket(Context context, String pkg) {
        try {
            Intent intent1 = new Intent(Intent.ACTION_VIEW);
            intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent1.setData(Uri.parse("market://details?id=".concat(pkg)));
            intent1.setPackage(context.getPackageName());
            if (intent1.resolveActivity(context.getPackageManager()) != null) {
                context.startActivity(intent1);
            } else {
                Intent intent2 = new Intent(Intent.ACTION_VIEW);
                intent2.setData(Uri.parse("http://play.google.com/store/apps/details?id=".concat(pkg)));
                intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (intent2.resolveActivity(context.getPackageManager()) != null) {
                    context.startActivity(intent2);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否是华为系统
     *
     * @return
     */
    public static boolean isHuawei() {
        String manufacturer = Build.MANUFACTURER;
        //这个字符串可以自己定义,例如判断华为就填写huawei,魅族就填写meizu
        return "huawei".equalsIgnoreCase(manufacturer);
    }

    /**
     * 检测是否是中兴机器
     */
    public static boolean isZte() {
        String manufacturer = Build.MANUFACTURER;
        //这个字符串可以自己定义,例如判断中兴
        return "zte".equalsIgnoreCase(manufacturer);
    }

    /**
     * 先跳转到google 市场，如果没有则跳转到对应的app 应用市场，否则就打开google 市场网页
     *
     * @param context
     * @param pkg
     */
    public static boolean isToGoogleMarket(final Context context, String pkg) {
        try {
            if (isInstallGooglePlay(context)) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setData(Uri.parse("market://details?id=".concat(pkg)));
                intent.setPackage("com.android.vending");//这里对应的是谷歌商店，跳转别的商店改成对应的即可
                context.startActivity(intent);
                return true;
            }

        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 是否安装了GOOGLE PLAY
     *
     * @param context
     * @return
     */
    public static boolean isInstallGooglePlay(Context context) {
        ApplicationInfo applicationInfo = null;
        try {
            applicationInfo = context.getPackageManager().getApplicationInfo("com.android.vending", 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            return applicationInfo != null && !TextUtils.isEmpty(applicationInfo.appComponentFactory);
        } else {
            return isInstallAppByPackageName(context, "com.android.vending");
        }
    }

    public static String getDefaultBrowserList(Context context) {
        PackageManager packageManager = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("http://"));
        StringBuffer sb = new StringBuffer();
        List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        if (activities != null) {
            for (ResolveInfo info : activities) {
                if (info != null && info.activityInfo != null) {
                    sb.append(info.activityInfo.packageName + " , ");
                }
            }
        }
        return sb.toString();
    }

    /**
     * 获取正在运动的亚马逊app
     *
     * @param context
     * @return
     */
    public static String getAmazonAppName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        Intent intent = new Intent();
        intent.setAction("com.amazon.identity.auth.device.authorization.MapAuthorizationService");
        List<ResolveInfo> intentServices = packageManager.queryIntentServices(intent, 0);
        StringBuffer stringBuffer = new StringBuffer();
        if (intentServices != null && intentServices.size() > 0) {
            for (ResolveInfo resolveInfo : intentServices) {
                if (resolveInfo == null || resolveInfo.serviceInfo == null) continue;
                if (!TextUtils.isEmpty(resolveInfo.serviceInfo.packageName)) {
                    ApplicationInfo applicationInfo = null;
                    try {
                        applicationInfo = packageManager.getApplicationInfo(resolveInfo.serviceInfo.packageName, PackageManager.GET_META_DATA);
                        stringBuffer.append(packageManager.getApplicationLabel(applicationInfo).toString() + ",");
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return stringBuffer.toString();
    }

    /**
     * 是否打开了读取通知的权限
     *
     * @return
     */
    public static boolean notificationEnabled(Context context) {
        if (context == null) return false;
        String flat = Settings.Secure.getString(context.getContentResolver(), "enabled_notification_listeners");
        if (!TextUtils.isEmpty(flat)) {
            return flat.contains(context.getPackageName());
        } else {
            return false;
        }
    }

    public static void toSelfSetting(Context context) {

        Intent mIntent = new Intent();
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            if (Build.VERSION.SDK_INT >= 9) {
                mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                mIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                mIntent.setAction(Intent.ACTION_VIEW);
                mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                mIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
            }
            context.startActivity(mIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 自启动
     */
    public static void setSelfStart(Context context) {
        if (RomUtils.isOneplus()) {
            launchOnePlusBootManagerSettings(context);
        } else if (RomUtils.isXiaomi()) {
            launchMiAppManager(context);
        } else if (RomUtils.isLenovo()) {
            launchLenovoSecurityCenter(context);
        } else if (RomUtils.isSamsung()) {
            launchSamsungBatterySettings(context);
        } else {
            goToSystemSetting(context);
        }
    }

    /**
     * 省电模式
     */
    public static void goSettingPSM(Context context) {
        if (RomUtils.isHonor() || RomUtils.isHuawei()) {
            try {
                // 构建打开华为手机管家的 Intent
                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.mainscreen.MainScreenActivity"));
                context.startActivity(intent);
            } catch (Exception e) {
                goToSystemSetting(context);
            }
        } else if (RomUtils.isOppo() || RomUtils.isRealme() || RomUtils.isGoogle()){
            goToApplicationSystemDetail(context);
        } else {
            goToSystemSetting(context);
        }
    }


    /**
     * 后台耗电保护
     */
    public static void setBackgroundBehavior(Context context) {
        if (RomUtils.isSamsung()) {
            goToApplicationSystemDetail(context);
        } else if (RomUtils.isOneplus() || RomUtils.isXiaomi()) {
            launchAndroidBatterySettings(context);
        } else if (RomUtils.isPoco()) {
            launchMiAppManager(context);
        } else if (RomUtils.isLenovo()) {
            launchLenovoSecurityCenter(context);
        } else if (RomUtils.isMeizu()) {
            launchMeizuPhoneManager(context);
        } else {
            goToSystemSetting(context);
        }
    }

    /**
     * 设置关联启动
     */
    public static void setAssociativeStart(Context context) {
        if (RomUtils.isVivo()) {
            goToSystemSetting(context);
        } else {
            goToSystemSetting(context);
        }
    }

    /**
     * 跳转系统设置界面
     */
    public static void goToSystemSetting(Context context){
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        context.startActivity(intent);
    }

    /**
     * 跳转应用详情页
     */
    public static void goToApplicationSystemDetail(Context context){
        try{
            // 否则跳转到应用详情
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", context.getPackageName(), null);
            intent.setData(uri);
            context.startActivity(intent);
        }catch (Exception e){
            goToSystemSetting(context);
        }
    }

    /**
     * 小米自启动
     */
    public static void launchMiAppManager(Context context) {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.securitycenter.main.MainActivity"));
            context.startActivity(intent);
        } catch (Exception e) {
            goToSystemSetting(context);
        }
    }

    public static boolean isPOCOPhoneManagerAppInstalled(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            packageManager.getPackageInfo("com.miui.securitycenter", PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 跳转三星电池界面
     * @param context
     */
    public static void launchSamsungBatterySettings(Context context) {
        goToSystemSetting(context);
//        try {
//            Intent intent = new Intent();
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.setComponent(new ComponentName("com.samsung.android.lool", "com.samsung.android.lool.battery.BatteryActivity"));
//            context.startActivity(intent);
//        } catch (Exception e) {
//            launchAndroidBatterySettings(context);
//        }
    }

    /**
     * 跳转Android系统电池界面
     *
     * @param context
     */
    public static void launchAndroidBatterySettings(Context context) {
        try {
            Intent intent = new Intent(Settings.ACTION_BATTERY_SAVER_SETTINGS);
            context.startActivity(intent);
        } catch (Exception e) {
            goToSystemSetting(context);
        }
    }

    /**
     * 一加手机跳转系统自启动
     */
    public static void launchOnePlusBootManagerSettings(Context context) {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.oneplus.security", "com.oneplus.security.startupmanagedapp.StartupManageAppActivity"));
            context.startActivity(intent);
        } catch (Exception e) {
            goToSystemSetting(context);
        }
    }

    /**
     * 魅族是否安装手机管家
     * @return
     */
    public static boolean isMeizuPhoneManagerAppInstalled(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            packageManager.getPackageInfo("com.meizu.safe", PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 跳转魅族手机管家
     *
     * @param context
     */
    public static void launchMeizuPhoneManager(Context context) {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.meizu.safe", "com.meizu.safe.ui.phoneoptimize.PhoneManagerActivity"));
            context.startActivity(intent);
        } catch (Exception e) {

        }
    }

    /**
     * 跳转联想安全中心
     */
    public static void launchLenovoSecurityCenter(Context context) {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.lenovo.safecenter", "com.lenovo.safecenter.MainService"));
            context.startActivity(intent);
        } catch (Exception e) {

        }
    }

    /**
     * 设置运动权限
     */
    public static void settingSportAssociate(Context context,String appName) {
        if(RomUtils.isHuawei()){
            ComponentName componentName = null;
            int sdkVersion = Build.VERSION.SDK_INT;
            try {
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //跳自启动管理
                if (sdkVersion >= 28){//9:已测试
                    componentName = ComponentName.unflattenFromString("com.android.settings/com.android.settings.HWSettings");//跳自启动管理
                }else if (sdkVersion >= 26){//8：已测试
                    componentName = ComponentName.unflattenFromString("com.huawei.systemmanager/.appcontrol.activity.StartupAppControlActivity");
                }else if (sdkVersion >= 23){//7.6：已测试
                    componentName = ComponentName.unflattenFromString("com.huawei.systemmanager/.startupmgr.ui.StartupNormalAppListActivity");
                }else if (sdkVersion >= 21){//5
                    componentName = ComponentName.unflattenFromString("com.huawei.systemmanager/com.huawei.permissionmanager.ui.MainActivity");
                }
                //componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity");//锁屏清理
                intent.setComponent(componentName);
                context.startActivity(intent);
            }catch (Exception e){
                //跳转失败
            }
        }else if(RomUtils.isXiaomi()){
            Intent intent = new Intent();
            try {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ComponentName componentName = null;
                componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity");
                intent.setComponent(componentName);
                context.startActivity(intent);
            } catch (Exception e) {//抛出异常就直接打开设置页面
                jumpAPPInfo(context);
            }
        }else if(RomUtils.isVivo()){
//            Intent localIntent;
//            try {
//                if (((Build.MODEL.contains("Y85")) && (!Build.MODEL.contains("Y85A"))) || (Build.MODEL.contains("vivo Y53L"))) {
//                    CommonLogUtil.d(TAG, "settingSportRight: "+"+++++++++");
//                    localIntent = new Intent();
//                    localIntent.setClassName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.PurviewTabActivity");
//                    localIntent.putExtra("packagename", context.getPackageName());
//                    localIntent.putExtra("tabId", "1");
//                    context.startActivity(localIntent);
//                } else {
//                    CommonLogUtil.d(TAG, "settingSportRight: "+"------------");
//                    localIntent = new Intent();
//                    localIntent.setClassName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.SoftPermissionDetailActivity");
//                    localIntent.setAction("secure.intent.action.softPermissionDetail");
//                    localIntent.putExtra("packagename", context.getPackageName());
//                    context.startActivity(localIntent);
//                }
//            }catch (Exception e){
//                // 否则跳转到应用详情
//                localIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//                Uri uri = Uri.fromParts("package",context.getPackageName(), null);
//                localIntent.setData(uri);
//                context.startActivity(localIntent);
//            }
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            context.startActivity(intent);
        }else if(RomUtils.isOppo()){
            Intent intent = new Intent();
            try {
                if (Build.VERSION.SDK_INT >= 23){
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    ComponentName comp = new ComponentName("com.coloros.safecenter",
                            "com.coloros.safecenter.startupapp.StartupAppListActivity");
                    intent.setComponent(comp);
                    context.startActivity(intent);
                }else {
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    ComponentName comp = new ComponentName("com.color.safecenter",
                            "com.color.safecenter.permission.startup.StartupAppListActivity");
                    intent.setComponent(comp);
                    context.startActivity(intent);
                }
            }catch (Exception e){
                try {
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("pkg_name", context.getPackageName());
                    intent.putExtra("app_name", appName);
                    intent.putExtra("class_name", "com.welab.notificationdemo.MainActivity");
                    ComponentName comp = new ComponentName("com.coloros.notificationmanager", "com.coloros" +
                            ".notificationmanager.AppDetailPreferenceActivity");
                    intent.setComponent(comp);
                    context.startActivity(intent);
                }catch (Exception e1){
                    // 否则跳转到应用详情
                    intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                    intent.setData(uri);
                    context.startActivity(intent);
                }
            }
        }
    }

    /**
     * 跳转到省电优化界面
     */
    private void setPower(Context context) {
        if(RomUtils.isXiaomi()){
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.miui.powerkeeper",
                    "com.miui.powerkeeper.ui.HiddenAppsConfigActivity"));
            //包名写在这里
            intent.putExtra("package_name", context.getPackageName());
            //app名字写在这里"
            intent.putExtra("package_label", context.getPackageName());
            context.startActivity(intent);
        }else if(RomUtils.isVivo()){
            Intent intent = new Intent();
            intent.setClassName("com.iqoo.powersaving",
                    "com.iqoo.powersaving.PowerSavingManagerActivity");
            //包名写在这里
            intent.putExtra("package_name", context.getPackageName());
            //app名字写在这里"
            context.startActivity(intent);
        }

    }

    /**
     * 抛出异常就直接打开设置页面
     */
    public static void jumpAPPInfo(Context context) {
        try {
            // MIUI 8
            Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
            localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
            localIntent.putExtra("extra_pkgname", context.getPackageName());
            context.startActivity(localIntent);
        } catch (Exception e) {
            try {
                // MIUI 5/6/7
                Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
                localIntent.putExtra("extra_pkgname", context.getPackageName());
                context.startActivity(localIntent);
            } catch (Exception e1) {
                // 否则跳转到应用详情
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                intent.setData(uri);
                context.startActivity(intent);
            }
        }
    }

    /**
     * 判断是否支持跳转手机管家
     * @param context
     * @return
     */
    public static boolean isHuaweiAppManagerInstalled(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            packageManager.getPackageInfo("com.huawei.systemmanager", PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 是否安装faceBook
     * @param context
     * @return
     */
    public static boolean isFacebookInstalled(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            packageManager.getPackageInfo("com.facebook.katana", 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            // Facebook app not installed
            return false;
        }
    }
}
